<template>
    <div>
        <Modal v-model="isShowModal" :title="title" @on-cancel="hide('formValidate')" :mask-closable="false">


            <Form ref="formValidate" :model="params" :rules="ruleValidate" :label-width="80">
                <FormItem label="名称：" prop="roleName">
                    <Input maxlength="128" v-model.trim="params.roleName" placeholder="请输入角色名称"></Input>
                </FormItem>
                <FormItem label="权限：" prop="roleContent">
                    <Tree ref="tree" :data="allRoleList" show-checkbox @on-check-change="onCheckChange"></Tree>
                </FormItem>
            </Form>


            <!-- 重写对话框底部按钮 -->
            <div slot="footer">
                <Button @click="hide('formValidate')">取消</Button>
                <Button v-if="type != 1" type="primary" @click="handleSubmit('formValidate')" :loading="loadingBtn">
                    <span v-if="!loadingBtn">确定</span>
                    <span v-else>请稍候...</span>
                </Button>
            </div>

        </Modal>
    </div>
</template>

<script>
    export default {
        name: "role-ope",
        data() {
            return {
                isShowModal: false,
                loadingBtn: false,
                title: '查看信息',
                type: 0,
                params: {
                    roleName: '',
                    roleContent: '',
                    adminRoleId: ''
                },
                allRoleList: [],
                currentUserRoleList: [],
                ruleValidate: {
                    roleName: [
                        {required: true, message: '角色名称不能为空', trigger: 'change'},
                        {max: 128, message: '角色名称过长', trigger: 'change'}
                    ],
                    roleContent: [
                        {required: true, message: '请至少选择一个权限', trigger: 'change'},
                    ]
                }
            }
        },
        mounted() {
            // 权限-获取所有的权限
            this.permissionList()
        },
        methods: {
            // 点击提交验证
            handleSubmit(name) {
                console.log(this.params);
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        // this.$Message.error('验证通过');
                        /**
                         * type判断
                         * 1.查看 2.新增 3.编辑
                         */
                        switch (this.type) {
                            case 1:
                                // 查看角色;
                                break;
                            case 2:
                                // 新增角色
                                this.addRole();
                                break;
                            case 3:
                                // 编辑角色
                                this.updateRole();
                                break;
                            default:
                                this.$Notice.error({
                                    title: '管理员管理',
                                    desc: '查看，新增，编辑区分判断报错',
                                    duration: 0
                                });
                                break
                        }
                    } else {
                        this.$Message.error('还有信息没有填写合格哦~');
                    }
                })
            },
            // 显示模态框
            show(type, row) {
                this.isShowModal = true;
                this.type = type;
                /**
                 * type判断
                 * 1.查看 2.新增 3.编辑
                 */
                switch (type) {
                    case 1:
                        this.title = '查看角色';
                        this.findRoleInfo(row);
                        break;
                    case 2:
                        this.title = '新增角色';
                        break;
                    case 3:
                        this.title = '编辑角色';
                        this.findRoleInfo(row);
                        break;
                    default:
                        this.$Notice.error({
                            title: '角色管理',
                            desc: '查看，新增，编辑模态框报错',
                            duration: 0
                        });
                        break
                }
            },
            // 添加角色
            addRole(){
                this.$Spin.show();
                this.axios.post('/adminRole/addRole', this.params).then(res => {
                    console.log(res);
                    setTimeout(()=>{
                        this.$Spin.hide();
                    },300);
                    if (res.status == 200) {
                        this.$emit('changeDate');
                        this.$Message.success('操作成功.');
                        this.hide('formValidate');
                    }
                    if(res.status == 201){
                        this.$Message.error(res.msg);
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '新增角色接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 编辑角色
            updateRole(){
                this.$Spin.show();
                this.axios.post('/adminRole/updateRole', this.params).then(res => {
                    console.log(res);
                    setTimeout(()=>{
                        this.$Spin.hide();
                    },300);
                    if (res.status == 200) {
                        this.$emit('changeDate');
                        this.$Message.success('操作成功.');
                        this.hide('formValidate');
                    }
                    if(res.status == 201){
                        this.$Message.error(res.msg);
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '编辑角色接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 查询管理员详情
            findRoleInfo(row){
                this.$Spin.show();
                this.axios.post('/adminRole/findRoleInfo', {
                    adminRoleId: row.adminRoleId
                }).then(res => {
                    console.log(res);
                    setTimeout(()=>{
                        this.$Spin.hide();
                    },300);
                    if (res.status == 200) {
                        // this.$Message.success('操作成功.');
                        this.params.roleName = res.data.roleName;
                        this.params.roleMark = res.data.roleMark;
                        this.params.adminRoleId = res.data.adminRoleId;
                        this.params.roleContent = res.data.roleContent;
                        // 回显树结构选中数据
                        this.treeDisplay(res.data.roleContent);
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '查看角色详情接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 根据查出的详情，回显树节点选中状态
            treeDisplay(data){
                let arr = data.split(',');
                if(arr.length){
                    for(let i in arr){
                        for(let x in this.allRoleList){
                            if(this.allRoleList[x].children.length){
                                for(let y in this.allRoleList[x].children){
                                    if(arr[i] === this.allRoleList[x].children[y].adminPermissionId){
                                        this.$set(this.allRoleList[x].children[y], 'checked', true)
                                    }
                                }
                            }
                        }
                    }
                }else{
                    this.$Notice.error({
                        title: '数据错误',
                        desc: '回显角色选中状态，分割数据报错',
                        duration: 0
                    });
                }
            },
            // 权限-获取所有的权限
            permissionList() {
                this.axios.post('/adminLogin/permissionList').then(res => {
                    console.log(res);
                    if (res.status == 200) {
                        this.allRoleList = res.data;
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '获取所有权限接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 树当前已勾选权限节点的数据
            onCheckChange() {
                // 获取树节点选中的权限
                let allNode = this.$refs.tree.getCheckedAndIndeterminateNodes();
                let arr = [];
                for (let i in allNode) {
                    arr.push(allNode[i].adminPermissionId)
                }
                // 将选中的树节点中的权限转成字符串
                if (arr.length) {
                    this.params.roleContent = arr.join(",");
                } else {
                    this.params.roleContent = '';
                }
                // 验证是否选中权限
                this.$refs['formValidate'].validateField('roleContent');
            },
            // 关闭模态框
            hide(name) {
                this.isShowModal = false;
                this.params.adminRoleId = '';
                // 初始化树节点所有权限，去掉选中的权限
                this.permissionList();
                this.$refs[name].resetFields();
                // console.log(this.params)
            }
        }
    }
</script>

<style scoped>

</style>